package com.china.zhuoyue.ui.activity.login

import android.view.View
import com.china.zhuoyue.api.login.launchUILogin
import com.china.zhuoyue.databinding.ActivityRegisterBinding
import com.china.zhuoyue.ui.api.ApiObserver
import com.china.zhuoyue.ui.base.BaseActivity
import com.china.zhuoyue.ui.cache.UserCache
import com.china.zhuoyue.ui.ext.toastMessageLong
import com.china.zhuoyue.ui.ext.value
import com.china.zhuoyue.ui.utils.variableView

class RegisterActivity : BaseActivity<ActivityRegisterBinding>() {

    override fun initView() {
        loadView {
            bindViewClick(
                buttonRegister,
                tbVcode,
            )
            variableView {
                addTextView(etPhone)
                addTextView(etPassword)
                addTextView(etVcode)
                addTextView(etDoublePassword)
                addOnValidationInterceptListener(::intercept)
                addOnValidationResultListener(buttonRegister)
            }
        }
    }

    private fun intercept(view: View): Boolean? = when (view) {
        vb.etPhone -> vb.tbVcode.enable(vb.etPhone.length() == 11)
        vb.etVcode -> vb.etVcode.length() == 6
        vb.etPassword -> vb.etPassword.length() in 6..16
        vb.etDoublePassword -> vb.etDoublePassword.length() in 6..16
        else -> null
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.tbVcode -> {
                launchUILogin({
                    sendSms(vb.etPhone.value, "001")
                }, ApiObserver(this) {
                    vb.tbVcode.start()
                })
            }
            vb.buttonRegister -> login()
        }
    }

    private fun login() {
        if (vb.etPassword.value != vb.etDoublePassword.value) {
            "两次密码输入不一致".toastMessageLong()
            return
        }
        launchUILogin({ register(vb.etPhone.value, vb.etPassword.value, vb.etVcode.value) },
            ApiObserver(this) {
                if (it != null) {
                    UserCache.saveToken(it.token)
                    UserCache.saveUserInfoBean(it)
                    setResult(RESULT_OK)
                    finish()
                }
            })
    }

}